import java.awt.*;
import java.awt.event.*;

public class LineTool implements Tool {
   
  protected DrawingCanvas canvas;
  protected Point startingMousePosition;
  protected Point currentMousePosition;
  protected Color saveColor;

  public LineTool(DrawingCanvas canvas) {
   this.canvas = canvas;
  }
  
  protected void drawLineSegment(Point p1, Point p2) {
    canvas.getImageBufferGraphics().drawLine(p1.x,p1.y,
				           p2.x, p2.y);
    /* redraw only the small rectangle  */
    /* containing the new line segment  */
    int x0 = Math.min(p1.x, p2.x);
    int y0 = Math.min(p1.y, p2.y);
    int dx = Math.abs(p2.x - p1.x)+ 1;
    int dy = Math.abs(p2.y - p1.y) + 1;
    canvas.repaint(x0, y0, dx, dy);
  }

 public void mousePressed(MouseEvent e)  {
   /* Establish starting point for next drawing */
   startingMousePosition = e.getPoint();
   currentMousePosition = startingMousePosition;
   Graphics iBGraphics = canvas.getImageBufferGraphics();
   saveColor = iBGraphics.getColor( );
   iBGraphics.setXORMode(Color.lightGray);
   iBGraphics.setColor(Color.white);
   drawLineSegment(startingMousePosition, startingMousePosition);
 }

 public void mouseDragged(MouseEvent e)  {
   /* erase temporary line */
   drawLineSegment(startingMousePosition,
				currentMousePosition);
   /* draw updated temporary line */
   Point newMousePosition = e.getPoint();
   drawLineSegment(startingMousePosition,
                                newMousePosition);
   /* update current mouse coordinates */
   currentMousePosition = newMousePosition;
 }


   public void mouseReleased(MouseEvent e) { 
     Graphics iBGraphics = canvas.getImageBufferGraphics();
     /* erase last temporary line */
     drawLineSegment(startingMousePosition,currentMousePosition);
     /* Reset the graphics context to normal paint mode, */
     /* restore pen color, and draw permanent line.      */
     iBGraphics.setPaintMode();
     iBGraphics.setColor(saveColor);
     drawLineSegment(startingMousePosition, e.getPoint());
     
     LineObject myline=new LineObject(startingMousePosition,e.getPoint(),canvas.getImageBufferGraphics().getColor());
     IDrawingObjectLink myLineLink=new IDrawingObjectLink(myline);
     myLineLink.next=canvas.firstObject;
     canvas.firstObject=myLineLink;
  }
}
